package com.xindaoapp.happypet.ui;

import java.io.File;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Html;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.socialize.sso.UMSsoHandler;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.activity.PictureListActivity;
import com.xindaoapp.happypet.adapter.EmptyAdapter;
import com.xindaoapp.happypet.adapter.PictureAdapter;
import com.xindaoapp.happypet.bean.SplashPictureBean;
import com.xindaoapp.happypet.bean.SplashPictureBean.SplashBannerInfo;
import com.xindaoapp.happypet.bean.SplashPictureBean.SplashPicture;
import com.xindaoapp.happypet.utils.BasePopupWindow;
import com.xindaoapp.happypet.utils.CommonParameter;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.Constants.PUBLISHPOSTS;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.view.waterfall.XListView;
import com.xindaoapp.happypet.view.waterfall.XListView.IXListViewListener;
import com.xindaoapp.happypet.view.waterfall.XListViewFooter;
import com.xindaoapp.share.SharePopupWindow;

/**
 * 首页--活动--活动详情页面
 * 
 * @author Yangqing
 * 
 */
public class SplashPictureActivity2 extends BaseActivity {

    private SplashPictureActivity2 mContext;
    private int currentPage = 1;
    private int count;
    private PictureAdapter pictureAdapter;
    private ImageView top_image;
    private TextView top_title, more_detail;
    private TextView top_add_activity, top_desc;
    private String actID = "";
    private String filter = "";
    private View foot;
    private TextView tv_hot, tv_new, currAdd;
    private final String ARTICLE = "article";
    private View share_friend;


    private SplashBannerInfo shaituinfo;
    private List<SplashPicture> pictureList;

    public String mCameraFilePath;
    private XListView pullRefreshStagGridView;
    private final int oldItemCount = 0;

    public enum LoadType {
        // PULLDOWN 下拉刷新
        // PULLUP 上拉加载
        PULLDOWN, PULLUP
    }


    @Override
    protected int getContentViewResId() {
        return R.layout.layout_splashpicture2;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.mContext = SplashPictureActivity2.this;
        super.onCreate(savedInstanceState);
    }


    @Override
    protected void initViews() {
        super.initViews();
        setTopBarTitle("活动详情");
        actID = getIntent().getStringExtra("actID");

        if (rightImageView != null)
            rightImageView.setClickable(false);

        ll_layout = findViewById(R.id.ll_layout);


        pullRefreshStagGridView = (XListView) findViewById(R.id.pullRefreshStagGridView);
        pullRefreshStagGridView.setPullRefreshEnable(false);
        pullRefreshStagGridView.setPullLoadEnable(true);
        pullRefreshStagGridView.setXListViewListener(mIXListViewListener);

        headerView = View.inflate(this, R.layout.item_splash_header, null);
        ll_top_search = headerView.findViewById(R.id.ll_top_search);
        btn_search = (Button) headerView.findViewById(R.id.iv_shop_search);
        et_search = (EditText) headerView.findViewById(R.id.et_search);
        top_view = headerView.findViewById(R.id.top_view);
        // top_view.setVisibility(View.GONE);
        top_image = (ImageView) headerView.findViewById(R.id.top_image);
        top_title = (TextView) headerView.findViewById(R.id.top_title);
        more_detail = (TextView) headerView.findViewById(R.id.more_detail);
        top_title.getBackground().setAlpha(100);
        top_desc = (TextView) headerView.findViewById(R.id.top_desc);
        top_add_activity = (TextView) headerView.findViewById(R.id.top_add_activity);

        tv_hot = (TextView) headerView.findViewById(R.id.tv_hot);
        tv_new = (TextView) headerView.findViewById(R.id.tv_new);
        // hot_line = headerView.findViewById(R.id.hot_line);
        // new_line = headerView.findViewById(R.id.new_line);

        currAdd = (TextView) findViewById(R.id.currAdd);
        share_friend = findViewById(R.id.share_friend);

        tv_hot.setOnClickListener(mOnClickListener);
        tv_new.setOnClickListener(mOnClickListener);
        headerView.findViewById(R.id.rl_new).setOnClickListener(mOnClickListener);
        headerView.findViewById(R.id.rl_hot).setOnClickListener(mOnClickListener);

        pullRefreshStagGridView.addHeaderView(headerView);


        pullRefreshStagGridView.setAdapter(pictureAdapter);
        getGridViewData(currentPage, LoadType.PULLDOWN);

    }


    private final IXListViewListener mIXListViewListener = new IXListViewListener() {

        @Override
        public void onRefresh() {
            if (et_search != null)
                et_search.getText().clear();
            isSearch = false;
            currentPage = 1;
            ll_layout.setVisibility(View.VISIBLE);
            getGridViewData(currentPage, LoadType.PULLDOWN);
        }

        @Override
        public void onLoadMore() {
            if ((count > (currentPage - 1) * 16) && !isSearch) {
                getGridViewData(++currentPage, LoadType.PULLUP);
            } else {
                pullRefreshStagGridView.stopLoadMore();
                // Toast.makeText(mContext, R.string.no_more_data, Toast.LENGTH_SHORT)
                // .show();
            }
        }
    };


    @Override
    protected void initEvents() {
        super.initEvents();
        more_detail.setOnClickListener(mOnClickListener);
        currAdd.setOnClickListener(mOnClickListener);
        share_friend.setOnClickListener(mOnClickListener);
        btn_search.setOnClickListener(mOnClickListener);
        et_search.setOnClickListener(mOnClickListener);
    }

    @Override
    protected void onLoadDatas() {
        super.onLoadDatas();
    }

    /**
     * 获取瀑布流数据
     */
    private void getGridViewData(int currentPage, final LoadType type) {

        getMoccaApi().getSplashPictureData(currentPage, 16, actID, filter,
                new IRequest<SplashPictureBean>() {
                    @Override
                    public void request(SplashPictureBean t) {
                        // pullRefreshStagGridView.onRefreshComplete();
                        if (t != null && t.shaituinfo != null) {
                            pullRefreshStagGridView.setRefreshTime(CommonUtil
                                    .formatPullToRefreshDate());
                            if (rightImageView != null)
                                rightImageView.setClickable(true);
                            onDataArrived(true);
                            shaituinfo = t.shaituinfo;

                            // 判断当前活动是否可以参加
                            if (Constants.AVTIVITY_CHAGNQI.equals(shaituinfo.status)
                                    || Constants.AVTIVITY_GOING.equals(shaituinfo.status)) {// 活动进行中
                                currAdd.setClickable(true);
                                currAdd.setBackgroundResource(R.drawable.splash_btn_left);
                            } else if (Constants.AVTIVITY_UNSTART.equals(shaituinfo.status)) {// 活动未开始，现已在活动首页做判断，未开始直接跳转h5页面
                                currAdd.setClickable(false);
                                currAdd.setBackgroundResource(R.drawable.splash_btn);
                            } else if (Constants.AVTIVITY_COMPLETE.equals(shaituinfo.status)) {// 活动完成
                                currAdd.setBackgroundResource(R.drawable.splash_btn_left);
                                currAdd.setClickable(true);
                                // currAdd.setText("查看榜单");
                            }
                            int mWidth = Integer.parseInt(shaituinfo.coverwidth);
                            int mHeight = Integer.parseInt(shaituinfo.coverheight);
                            top_image
                                    .setLayoutParams(new RelativeLayout.LayoutParams(
                                            LayoutParams.MATCH_PARENT,
                                            (int) ((float) CommonParameter.sScreenWidth / mWidth * mHeight)));
                            // 200));

                            if (!TextUtils.isEmpty(t.shaituinfo.coverpath)) {
                                ImageLoader.getInstance().displayImage(t.shaituinfo.coverpath,
                                        top_image);
                            } else {
                                top_image.setBackgroundResource(R.drawable.picture_loading);
                            }

                            top_title.setText(t.shaituinfo.tag);
                            top_desc.setText(t.shaituinfo.message);
                            // 活动为比赛时，直接显示更多按钮
                            if (Constants.TYPE_GAME.equals(shaituinfo.type)) {
                                more_detail.setVisibility(View.VISIBLE);
                            } else {
                                // 为活动时，如果htmlurl不为空，显示更多按钮
                                if (!TextUtils.isEmpty(t.shaituinfo.htmlurl))
                                    more_detail.setVisibility(View.VISIBLE);
                            }
                        }

                        if (t != null && t.array != null) {

                            pictureList = t.array;
                            if (pullRefreshStagGridView.getVisibility() == View.GONE) {
                                pullRefreshStagGridView.setVisibility(View.VISIBLE);
                            }
                            count = Integer.parseInt(t.total);
                            top_add_activity.setText(Html.fromHtml(String.format(getResources()
                                    .getString(R.string.splash_add_activity), count)));

                            if (type.ordinal() == LoadType.PULLDOWN.ordinal()) {
                                // ll_top_search.setVisibility(View.VISIBLE);
                                if (pictureAdapter == null || top_view.getVisibility() == View.GONE) {
                                    pictureAdapter = new PictureAdapter(mContext, t.array);
                                    pullRefreshStagGridView.setAdapter(pictureAdapter);
                                } else {
                                    pictureAdapter.clearItem();
                                    pictureAdapter.addItem(t.array);
                                    pictureAdapter.notifyDataSetChanged();
                                }
                                pullRefreshStagGridView.stopRefresh();
                            } else {
                                pictureAdapter.addItem(t.array);
                                pullRefreshStagGridView.stopLoadMore();
                            }
                            top_view.setVisibility(View.VISIBLE);
                            // pictureAdapter.notifyDataSetChanged();
                        } else {
                            onDataArrived(false);
                            if (type.ordinal() == LoadType.PULLDOWN.ordinal()) {
                                pullRefreshStagGridView.stopRefresh();
                            } else {
                                pullRefreshStagGridView.stopLoadMore();

                            }
                        }
                    }
                });
    }

    /**
     * 加载更多的H5页面
     * 
     * @param htmlurl
     */
    private void loadHTML5(String htmlurl) {
        Intent intent = new Intent(SplashPictureActivity2.this, ProgressBarWebViewActivity.class);
        intent.putExtra(Constants.KEY_VIDEO_URL, htmlurl);
        intent.putExtra(Constants.KEY_TOP_BAR_TITLE, "活动详情");
        startActivity(intent);
    }

    private final OnClickListener mOnClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.tv_hot:
                case R.id.rl_hot:// 最热
                    currentPage = 1;
                    initTextView();
                    tv_hot.setTextColor(getResources().getColor(R.color.splash_pic_text_color));
                    // hot_line.setVisibility(View.VISIBLE);
                    if (!"".equals(filter)) {
                        filter = "";
                        getGridViewData(currentPage, LoadType.PULLDOWN);
                    }
                    break;
                case R.id.tv_new:
                case R.id.rl_new:// 最新
                    currentPage = 1;
                    initTextView();
                    tv_new.setTextColor(getResources().getColor(R.color.splash_pic_text_color));
                    // new_line.setVisibility(View.VISIBLE);
                    if (!"dateline".equals(filter)) {
                        filter = "dateline";
                        getGridViewData(currentPage, LoadType.PULLDOWN);
                    }
                    break;
                case R.id.more_detail:
                    // loadHTML5(shaituinfo.htmlurl);
                    Intent intent = new Intent(mContext, PostDetailActivity.class);
                    intent.putExtra(Constants.KEY_POST_TID, shaituinfo.htmlurl);
                    intent.putExtra(Constants.KEY_FROM_ACTIVITY, true);
                    mContext.startActivity(intent);
                    break;

                case R.id.currAdd:// 立即参加

                    if (UserState.isLogged(SplashPictureActivity2.this)) {

                        // TODO 目前在右上角加查看榜单入口，该入口暂时取消201411211320
                        // if (Constants.AVTIVITY_CHAGNQI.equals(shaituinfo.status)
                        // || Constants.AVTIVITY_GOING.equals(shaituinfo.status)) {// 活动进行中
                        showSelectModeWindow();
                        // } else if (Constants.AVTIVITY_COMPLETE.equals(shaituinfo.status)) {//
                        // 活动完成
                        // // TODO 跳转查看榜单页面
                        // startActivity(new Intent(mContext, SeeRankingListActivity.class));
                        // }
                    }
                    break;
                case R.id.share_friend:// 告诉朋友
                    share();
                    break;

                case R.id.iv_shop_search:// 搜索帖子
                    isSearch = true;
                    SearchPostByUser();
                    hideKeyBoard();
                    pullRefreshStagGridView.mFooterView
                            .setState(XListViewFooter.STATE_REFRESHCOMPLETE);
                    break;

            }
        }

        /**
         * 搜索用户
         */
        private void SearchPostByUser() {
            String searchText = et_search.getText().toString().trim();
            // String searchText = "";
            if (TextUtils.isEmpty(searchText)) {
                Toast.makeText(mContext, "请输入关键字", Toast.LENGTH_SHORT).show();
                return;
            }

            final ProgressDialog progressDialog =
                    ProgressDialog.show(mContext, null, "获取数据中...", true);
            progressDialog.setCancelable(true);
            progressDialog.setCanceledOnTouchOutside(true);
            getMoccaApi().getPostByUser(searchText, new IRequest<SplashPictureBean>() {

                @Override
                public void request(SplashPictureBean t) {
                    if (progressDialog != null)
                        progressDialog.dismiss();
                    if (t != null) {
                        top_view.setVisibility(View.GONE);
                        if (pictureAdapter == null) {
                            pictureAdapter = new PictureAdapter(mContext, t.array);
                            pullRefreshStagGridView.setAdapter(pictureAdapter);
                        } else {
                            pictureAdapter.clearItem();
                            pictureAdapter.addItem(t.array);
                        }
                        pictureAdapter.notifyDataSetChanged();
                    } else {
                        ll_layout.setVisibility(View.GONE);
                        pullRefreshStagGridView.setAdapter(new EmptyAdapter(mContext));
                        // onDataArrivedEmpty();
                    }
                }
            });
        }

        private void initTextView() {
            tv_hot.setTextColor(getResources().getColor(R.color.tv_hot));
            tv_new.setTextColor(getResources().getColor(R.color.tv_hot));
            // hot_line.setVisibility(View.GONE);
            // new_line.setVisibility(View.GONE);
        }
    };
    private SharePopupWindow win;
    private View ll_top_search;
    private View ll_search;
    private Button btn_search;
    private EditText et_search;
    private View headerView;
    // 是否为搜索
    private boolean isSearch = false;


    private View top_view;// headerView 的头布局
    private View ll_layout;


    private void share() {
        if (UserState.isLogged(SplashPictureActivity2.this)) {
            win = new SharePopupWindow(SplashPictureActivity2.this, shaituinfo.coverpath, false);
            win.setDefaultIconId(R.drawable.icon);
            win.setPostCome("shaitu");
            String url =
                    String.format(
                            "http://bbs.chinapet.com/plugin.php?id=leepet_thread:shaitushow&shaituid=%1$s&uid=%2$s",
                            shaituinfo.actid, UserState.getUserUid());

            String contant =
                    String.format(
                            "#尾巴圈宠物# 尾巴圈正在举行%1$s活动,还有更多有趣的活动，快来参加吧!，@尾巴圈，我的养宠神器！下载地址：%2$s（来自@尾巴圈）",
                            shaituinfo.tag, url);

            String WXContant = String.format("尾巴圈正在举行%s活动，快来参加吧", shaituinfo.tag);

            String QQContant = String.format("尾巴圈正在进行%s活动，快来参加吧", shaituinfo.tag);


            win.setInfors(SplashPictureActivity2.this, contant, "尾巴圈，我的养宠神器", contant, WXContant,
                    QQContant, url).showAtLocation(findViewById(R.id.ll_layout), Gravity.BOTTOM, 0,
                    0);
            // win.setInfors(SplashPictureActivity2.this, contant, contant, contant, url)
            // .showAtLocation(findViewById(R.id.ll_layout), Gravity.BOTTOM, 0, 0);

            CommonUtil.addScreenBg(win, SplashPictureActivity2.this);
        }
    }



    @Override
    protected int getTopBarLeftImageViewRes() {
        return R.drawable.top_bar_back;
    }

    @Override
    protected OnClickListener getLeftViewClickListener() {
        return new OnClickListener() {
            @Override
            public void onClick(View v) {
                SplashPictureActivity2.this.finish();
            }
        };
    }


    /**
     * 立即参加，调出相机和相册
     */
    private void showSelectModeWindow() {
        final BasePopupWindow popupWindow = new BasePopupWindow(this);
        View view = View.inflate(getBaseContext(), R.layout.pop_select_post_mode, null);
        CommonUtil.addScreenBg(popupWindow, this);
        view.findViewById(R.id.btn_camera).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                popupWindow.dismiss();
                takePhoto();
            }
        });
        view.findViewById(R.id.btn_photos).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                popupWindow.dismiss();
                Intent intent = new Intent(getBaseContext(), PictureListActivity.class);
                intent.putExtra(Constants.KEY_SELECT_PICTURE_MODE, true);
                intent.putExtra(Constants.KEY_SHAITUINFO, shaituinfo);
                // intent.putExtra(Constants.KEY_TAGID, shaituinfo.tagid);
                // intent.putExtra(Constants.KEY_TAG, shaituinfo.tag);
                startActivity(intent);
            }
        });
        view.findViewById(R.id.btn_cancel).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                popupWindow.dismiss();
            }
        });
        popupWindow.init(view).showAtLocation(findViewById(R.id.all),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PUBLISHPOSTS.CAMERA && resultCode == RESULT_OK) {// 拍照完成
            // 跳转发帖页面，并传递图片地址
            Intent intent = new Intent(getBaseContext(), PostMessageActivity.class);
            intent.putExtra(Constants.KEY_CAMERA_PICTURE_PATH, mCameraFilePath);
            intent.putExtra(Constants.KEY_SHAITUINFO, shaituinfo);
            startActivity(intent);
            finish();
        }

        if (null != win) {
            UMSsoHandler ssoHandler = win.mController.getConfig().getSsoHandler(requestCode);
            if (ssoHandler != null) {
                ssoHandler.authorizeCallBack(requestCode, resultCode, data);
            }
        }


    }

    // private MyViewPager gridViewpager;

    /**
     * 拍照
     */
    private void takePhoto() {
        mCameraFilePath =
                Environment.getExternalStorageDirectory().getAbsolutePath() + "/happypet/pic"
                        + File.separator + System.currentTimeMillis() + ".jpg";
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
        startActivityForResult(intent, PUBLISHPOSTS.CAMERA);
    }

    @Override
    protected int getTopBarRightTextViewRes() {
        return R.string.activity_picture_seeranking;
        // return 0;
    }

    @Override
    // 查看榜单
    protected OnClickListener getRightViewClickListener() {
        return new OnClickListener() {
            @Override
            public void onClick(View v) {
                // Toast.makeText(mContext, "查看榜单", 0).show();
                Intent intent =
                        new Intent(SplashPictureActivity2.this, SeeRankingListActivity.class);
                intent.putExtra(Constants.KEY_TID, actID).putExtra("aa", "123");
                intent.putExtra(Constants.KEY_SHAITUINFO, shaituinfo);
                startActivity(intent);
            }
        };
    }

}
